package com.lin.service.lifecomments;

import com.lin.common.constant.CommonConstant;
import com.lin.common.error.CustomRuntimeException;
import com.lin.common.error.ErrorCode;
import com.lin.common.utils.DateUtils;
import com.lin.common.utils.RedisSerializableUtils;
import com.lin.controller.req.AddCommentsReqMsg;
import com.lin.dao.CommentsMapper;
import com.lin.dao.LifeMapper;
import com.lin.po.Comments;
import com.lin.po.Life;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CommentsServiceImpl implements CommentsService {
    private static Logger log = LoggerFactory.getLogger(CommentsServiceImpl.class);

    @Autowired
    private LifeMapper lifeMapper;
    @Autowired
    private CommentsMapper commentsMapper;

    @Override
    public Integer addcomments(AddCommentsReqMsg reqMsg) throws CustomRuntimeException {
        Life life = lifeMapper.selectByPrimaryKey(reqMsg.getLifeId());
        if (null == life) {
            throw new CustomRuntimeException(ErrorCode.LIFE_NOT_EXISTS, ErrorCode.LIFE_NOT_EXISTS.getMessage());
        }
        if (reqMsg.getParentId().equals(Comments.PARENTID_FIRST)) {
            Comments c = build(reqMsg, CommonConstant.FIRST_FLOOR);
            return commentsMapper.insertSelective(c);
        } else {
            //floor数据库操作，在第一次评论的楼层上新增1
            Comments c = build(reqMsg, null);
            return commentsMapper.replyinsert(c);
        }
    }

        private Comments build(AddCommentsReqMsg reqMsg, Integer floor) throws CustomRuntimeException {
        Comments c = new Comments();
        c.setId(Long.parseLong(RedisSerializableUtils.generateForLong(CommonConstant.DEFAULT_LENGTH)));
        c.setParentId(reqMsg.getParentId());
        c.setLifeId(reqMsg.getLifeId());
        c.setCustomerId(reqMsg.getCustomerId());
        c.setContents(reqMsg.getContents());
        c.setFloor(floor);
        c.setCreateTime(DateUtils.fullDateFormat());
        c.setUpdateTime(DateUtils.fullDateFormat());
        return c;
    }
}
